﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;

namespace FACUI.BasicClass
{

    public static class Util
    {
        private static string applicationPath = "";
        private static char[] splitChars = new char[] { ',', '，', '@' };
        
        [DllImport("Kernel32.dll")]
        public static extern bool CloseHandle(IntPtr hObject);
        public static bool CompareDcName(string name1, string name2)
        {
            if ((name1 != null) && (name2 != null))
            {
                try
                {
                    if (name2.Contains("/") && name1.Contains("/"))
                    {
                        if ((((name1.Split(new char[] { '/' })[0] == name2.Split(new char[] { '/' })[1]) || (name1.Split(new char[] { '/' })[0] == name2.Split(new char[] { '/' })[0])) || ((name1.Split(new char[] { '/' })[1] == name2.Split(new char[] { '/' })[1]) || (name1.Split(new char[] { '/' })[1] == name2.Split(new char[] { '/' })[0]))) || (name1 == name2))
                        {
                            return true;
                        }
                    }
                    else
                    {
                        int num;
                        if (name2.Contains("/"))
                        {
                            if ((((name1.Split(new char[] { '-' })[0] == name2.Split(new char[] { '/' })[1]) || (name1.Split(new char[] { '-' })[0] == name2.Split(new char[] { '/' })[0])) || ((name1 == name2.Split(new char[] { '/' })[0]) || (name1 == name2.Split(new char[] { '/' })[1]))) || (name1 == (num = Convert.ToInt32(name2.Split(new char[] { '/' })[0]) + 2).ToString()))
                            {
                                return true;
                            }
                        }
                        else if (name1.Contains("/"))
                        {
                            if (name1.Contains("-"))
                            {
                                if ((((name1.Split(new char[] { '-' })[0] == name2) || (name1.Split(new char[] { '-' })[1] == name2)) || ((name1 == name2.Split(new char[] { '/' })[0]) || (name1 == name2.Split(new char[] { '/' })[1]))) || (name1 == (num = Convert.ToInt32(name2.Split(new char[] { '/' })[0]) + 2).ToString()))
                                {
                                    return true;
                                }
                            }
                            else if (((name1 == name2) || (name1.Split(new char[] { '/' })[0] == name2)) || (name1.Split(new char[] { '/' })[1] == name2))
                            {
                                return true;
                            }
                        }
                        else if (((((name1 == name2) || (name1.Split(new char[] { '-' })[0] == name2)) || ((name1 == name2.Replace("-", "")) || (name1 == name2.Split(new char[] { '-' })[0]))) || (((name1.Replace("-", "") == name2) || (name1 == name2.Split(new char[] { 'J' })[0])) || ((name1 == name2.Split(new char[] { 'X' })[0]) || (name2 == name1.Split(new char[] { 'J' })[0])))) || (name2 == name1.Split(new char[] { 'X' })[0]))
                        {
                            return true;
                        }
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
            }
            return false;
        }

        public static bool CompressFile(string srcFile, string compressedFile)
        {
            if (!File.Exists(srcFile))
            {
                return false;
            }
            FileStream stream = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.None);
            byte[] buffer = new byte[stream.Length];
            if (stream.Read(buffer, 0, buffer.Length) != buffer.Length)
            {
                return false;
            }
            return CompressFile(buffer, compressedFile);
        }

        public static bool CompressFile(StationCfg staCfg, string compressedFile)
        {
            if (staCfg == null)
            {
                return false;
            }
            CfgNode staCfgRoot = staCfg.GetStaCfgRoot();
            if (string.IsNullOrEmpty(staCfgRoot.NodeCfgFileName))
            {
                return false;
            }
            IniFile iniFile = new IniFile(staCfgRoot.NodeCfgFileName);
            CfgNode.SaveSubNodesToCfgFile(iniFile, staCfgRoot);
            return CompressFile(iniFile.GetBytes(), compressedFile);
        }

        public static bool CompressFile(byte[] buffer, string compressedFile)
        {
            if (buffer == null)
            {
                return false;
            }
            FileStream stream = null;
            GZipStream stream2 = null;
            try
            {
                stream = new FileStream(compressedFile, FileMode.Create, FileAccess.ReadWrite);
                stream2 = new GZipStream(stream, CompressionMode.Compress);
                stream2.Write(buffer, 0, buffer.Length);
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                if (stream2 != null)
                {
                    stream2.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                }
            }
            return true;
        }

        public static bool ContainChinese(string str)
        {
            char[] chArray = str.ToCharArray();
            foreach (char ch in chArray)
            {
                if (ch > '\x00ff')
                {
                    return true;
                }
            }
            return false;
        }

        public static bool ContainEnglish(string str)
        {
            char[] chArray = str.ToCharArray();
            foreach (char ch in chArray)
            {
                if ((ch < '\x00ff') && (ch > '\0'))
                {
                    return true;
                }
            }
            return false;
        }

        public static int ConvertToInt(string text, int defVal)
        {
            try
            {
                return Convert.ToInt32(text);
            }
            catch (Exception)
            {
                return defVal;
            }
        }

        public static void CreateDir(string path)
        {
            int startIndex = path.LastIndexOf('\\');
            int num2 = path.LastIndexOf('/');
            if (startIndex < num2)
            {
                startIndex = num2;
            }
            if ((startIndex > 0) && (path.IndexOf('.', startIndex) > 0))
            {
                path = path.Substring(0, startIndex);
            }
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        [DllImport("Kernel32.dll")]
        public static extern IntPtr CreateEvent(IntPtr lp, bool bManualReset, bool bInitialState, string name);
        public static Image CreateImage(byte[] buf)
        {
            if (buf == null)
            {
                return null;
            }
            try
            {
                MemoryStream stream = new MemoryStream(buf);
                return Image.FromStream(stream);
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static bool Exist(string[] strs, string str)
        {
            if (strs != null)
            {
                foreach (string str2 in strs)
                {
                    if (str2 == str)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        
        public static string GetApplicationPath()
        {
            if (applicationPath != "")
            {
                return applicationPath;
            }
            string[] strArray = Application.ExecutablePath.Split(new char[] { '\\' });
            string str = "";
            if (strArray.Length > 1)
            {
                for (int i = 0; i < (strArray.Length - 1); i++)
                {
                    str = str + strArray[i];
                    if (i != (strArray.Length - 1))
                    {
                        str = str + @"\";
                    }
                }
            }
            applicationPath = str;
            return str;
        }

        public static int GetComboxIndex(ComboBox cmbBox, string str)
        {
            for (int i = 0; i < cmbBox.Items.Count; i++)
            {
                if (cmbBox.Items[i].ToString() == str)
                {
                    return i;
                }
            }
            return 0;
        }

        public static byte[] GetImageBuf(Image image)
        {
            if (image == null)
            {
                return null;
            }
            MemoryStream stream = new MemoryStream();
            try
            {
                image.Save(stream, ImageFormat.Bmp);
            }
            catch (ExternalException)
            {
                return null;
            }
            catch (ArgumentNullException)
            {
                return null;
            }
            return stream.GetBuffer();
        }

        public static Image GetImageOnOpenFileDlg()
        {
            try
            {
                OpenFileDialog dialog = new OpenFileDialog
                {
                    Filter = "位图(*.bmp)|*.bmp|JPG文件|*.jpg"
                };
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    return Image.FromFile(dialog.FileName);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("图片格式错误！请选择正确的图片格式", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            return null;
        }

        public static int Getint(string str)
        {
            int num = 0;
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Trim();
                char[] chArray = str.ToCharArray();
                for (int i = 0; i < chArray.Length; i++)
                {
                    if (chArray[i] > '\x00ff')
                    {
                        num++;
                    }
                }
            }
            return num;
        }

        public static int GetMaxColumnLength(CfgNode cfgnode, string column)
        {
            int num = 0;
            if ((cfgnode == null) || string.IsNullOrEmpty(column))
            {
                return 0;
            }
            foreach (CfgNode node in cfgnode.GetSubNodeList())
            {
                char[] chArray = node.GetValue(column).ToCharArray();
                int length = node.GetValue(column).Length;
                for (int i = 0; i < chArray.Length; i++)
                {
                    if (chArray[i] > '\x00ff')
                    {
                        length++;
                    }
                }
                if (length > num)
                {
                    num = length;
                }
            }
            return (num + 3);
        }

        [DllImport("Kernel32.dll")]
        public static extern uint GetTickCount();
        public static string GetTimeString(DateTime time)
        {
            return time.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static bool isNumberic(string message)
        {
            Regex regex = new Regex(@"^\d+$");
            return regex.IsMatch(message);
        }

        [DllImport("IsRunning.dll")]
        public static extern bool IsRunning2(string sMutexName);
        
        public static T[] NewObjects<T>(T[] t) where T : new()
        {
            if (t != null)
            {
                for (int i = 0; i < t.Length; i++)
                {
                    T local = default(T);
                    t[i] = (local == null) ? Activator.CreateInstance<T>() : (local = default(T));
                }
            }
            return t;
        }

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr PostMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk);
        public static string Replace(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Replace("-L", "").Replace("-U", "").Replace("-H", "").Replace("-QH", "").Replace("-B", "").Replace("_1DQJ", "");
            }
            return str;
        }

        public static string Replace(string str, bool b)
        {
            StringBuilder builder = new StringBuilder(str);
            if (b)
            {
                return builder.Replace("*", "*0").Replace("\r", "*1").Replace("\n", "*2").Replace("\t", "*3").Replace(" ", "*4").ToString();
            }
            return builder.Replace("*1", "\r").Replace("*2", "\n").Replace("*3", "\t").Replace("*4", " ").Replace("*0", "*").ToString();
        }

        public static bool sbIsExist(string sbName, CfgNode sbNode)
        {
            return sbIsExist(sbName, sbNode, false);
        }

        public static bool sbIsExist(string sbName, CfgNode sbNode, bool b)
        {
            if (sbNode != null)
            {
                sbName = sbName.Trim();
                if ((string.IsNullOrEmpty(sbName) || (sbName == "NULL")) || (sbNode.GetSubNode("设备列表") == null))
                {
                    return true;
                }
                foreach (CfgNode node in sbNode.GetSubNode("设备列表").GetSubNodeList())
                {
                    if (b && node["设备名称"].StartsWith(sbName))
                    {
                        return true;
                    }
                    if (sbName == node["设备名称"].Trim())
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public static void SetEnumDict(string enumStr, Dictionary<string, int> dict)
        {
            if (!string.IsNullOrEmpty(enumStr))
            {
                char[] separator = new char[] { ':' };
                dict.Clear();
                string[] strArray = SplitTrimString(enumStr, false);
                if ((strArray != null) && (strArray.Length != 0))
                {
                    foreach (string str in strArray)
                    {
                        string[] strArray2 = str.Split(separator);
                        if ((strArray2 != null) && (strArray2.Length >= 2))
                        {
                            int num = int.Parse(strArray2[0]);
                            dict[strArray2[1].Trim()] = num;
                        }
                    }
                }
            }
        }

        [DllImport("Kernel32.dll")]
        public static extern bool SetEvent(IntPtr hEvent);
        [DllImport("IsRunning.dll")]
        public static extern bool SetWndProp(IntPtr hWnd, string sMutexName);
        public static void ShowCfgError(string strError)
        {
            MessageBox.Show(strError, "配置错误！", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        }     

        public static string[] SplitTrimString(string str)
        {
            return SplitTrimString(str, false);
        }

        public static string[] SplitTrimString(string str, bool bToUpper)
        {
            string[] strArray = str.Split(splitChars);
            if ((strArray != null) && (strArray.Length > 0))
            {
                int num2;
                int num = 0;
                for (num2 = 0; num2 < strArray.Length; num2++)
                {
                    strArray[num2] = strArray[num2].Trim();
                    if (strArray[num2] != "")
                    {
                        num++;
                        if (bToUpper)
                        {
                            strArray[num2] = strArray[num2].ToUpper();
                        }
                    }
                }
                if (num > 0)
                {
                    string[] strArray2 = new string[num];
                    int num3 = 0;
                    for (num2 = 0; num2 < strArray.Length; num2++)
                    {
                        if (strArray[num2] != "")
                        {
                            if (bToUpper)
                            {
                                strArray[num2] = strArray[num2].ToUpper();
                            }
                            strArray2[num3++] = strArray[num2];
                        }
                    }
                    return strArray2;
                }
            }
            return null;
        }

        public static float ToFloat(string val, float defVal)
        {
            if (string.IsNullOrEmpty(val))
            {
                return defVal;
            }
            try
            {
                return Convert.ToSingle(val);
            }
            catch (Exception)
            {
                return defVal;
            }
        }

        public static int ToInt(string val, int defVal)
        {
            if (string.IsNullOrEmpty(val))
            {
                return defVal;
            }
            try
            {
                return int.Parse(val);
            }
            catch (Exception)
            {
                return defVal;
            }
        }

        public static string[] trim(string[] strs)
        {
            if (strs == null)
            {
                return null;
            }
            for (int i = 0; i < strs.Length; i++)
            {
                strs[i] = strs[i].Trim();
            }
            return strs;
        }

        public static DateTime UnixTime2DateTime(uint unixtime)
        {
            DateTime time = new DateTime(0x7b2, 1, 1, 8, 0, 0);
            return time.AddSeconds((double)unixtime);
        }

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        [Flags]
        public enum KeyModifiers
        {
            Alt = 1,
            Ctrl = 2,
            None = 0,
            Shift = 4,
            wnd = 8
        }
    }
}

